<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="姓名" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="应聘岗位" prop="stationName">
        <el-input v-model="queryParams.stationName" placeholder="请输入岗位名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item label="学历" prop="userEducation">
        <el-select v-model="queryParams.userEducation" placeholder="请选择岗位学历">
          <el-option label="全部" value=""></el-option>
          <el-option v-for="(item, index) in stationEduList" :key="index" :label="item" :value="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工作经验" prop="stationLesson">
        <el-select v-model="queryParams.stationLesson" placeholder="请选择岗位经验">
          <el-option label="全部" value=""></el-option>
          <el-option v-for="(item, index) in workExperienceList" :key="index" :label="item" :value="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="出生日期" prop="birthTime">
        <el-date-picker clearable v-model="queryParams.birthTime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择出生日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item v-if="!isCompany" label="招聘会" prop="careerId">
        <el-select v-model="queryParams.careerId" placeholder="请选择招聘会">
          <el-option label="全部" value=""></el-option>
          <el-option v-for="item in careerFairList" :key="item.id" :label="item.careerTitle"
            :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="应聘单位" prop="compId">
        <!-- <el-select v-model="queryParams.compId" placeholder="请选择应聘单位">
          <el-option label="全部" value=""></el-option>
          <el-option v-for="(item, index) in companyList" :key="index" :label="item.compName" :value="item.id"></el-option>
        </el-select> -->
        <!-- <el-cascader :props="props"></el-cascader> -->
        <el-cascader v-model="selectedValue" :clearable="true" :props="cascaderProps" placeholder="请选择" style="width: 360px;" @change="handleSelectCascader"></el-cascader>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExportList"
          v-hasPermi="['system:userResume:export']">列表导出</el-button>
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:userResume:export']">附件导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userResumeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="编号" align="center" prop="id" /> -->
      <el-table-column label="用户ID" align="center" prop="userId" />
      <el-table-column label="姓名" align="center" prop="userName" />
      <el-table-column label="性别" align="center" prop="userSex">
        <template slot-scope="scope">
          <span v-if="scope.row.userSex === 1">男</span>
          <span v-if="scope.row.userSex === 2">女</span>
        </template>
      </el-table-column>
      <el-table-column label="出生日期" align="center" prop="birthTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.birthTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="参与工作时间" align="center" prop="workTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.workTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="毕业学校" align="center" prop="userSchool" />
      <el-table-column label="学历" align="center" prop="userEducation" />
      <el-table-column label="专业" align="center" prop="userMajor" />
      <el-table-column label="工作经验" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.workYear + '年' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="应聘岗位" align="center" prop="stationName" />
      <el-table-column label="应聘渠道" align="center" prop="careerTitle" />
      <el-table-column v-if="!isCompany" label="应聘单位" align="center" prop="compName" />
      <el-table-column label="投递时间" align="center">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.overTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="isCompany" label="招聘状态" align="center" prop="isFollowText" />
      <el-table-column label="附件" align="center" prop="fileName">
        <template slot-scope="scope">
          <span style="color: #1890ff;cursor: pointer; text-decoration: underline;"
            @click="handleDownload(scope.row)">{{ scope.row.fileName }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="isCompany" label="是否联系" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.isRelateBool" @change="handleChangeStatus(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:userResume:view']">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <el-dialog title="简历信息" :visible.sync="showResume" width="50%" append-to-body>
      <resume :resumeData="resumeData"></resume>
      <div slot="footer" class="dialog-footer" v-if="isCompany">
        <el-button type="primary" @click="handleFollow">{{ resumeData.isFollow === 1 ? '取消关注' : '关 注' }}</el-button>
        <el-button @click="showResume = false">跳 过</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import resume from './resume.vue';
import { getHireDicts } from '@/api/system/dict/data'
import { listCareerFair } from "@/api/system/careerFair";
import { listUserResume, getUserResume, delUserResume, addUserResume, updateCompanyResume, exportList } from "@/api/system/userResume";
import { listStation } from "@/api/system/station";
import { listCompany } from "@/api/system/company";

export default {
  name: "UserResume",
  components: {
    resume
  },
  data() {
    return {
      showResume: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户简历信息表格数据
      userResumeList: [],
      resumeData: {},
      stationEduList: [],
      workExperienceList: [],
      companyList: [],

      selectedValue: [],
      // 弹出层标题
      title: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        careerId: null,
        compId: null,
        stationId: null,
        userName: null,
        userSex: null,
        birthTime: null,
        stationName: null,
        userEducation: null,
        stationLesson: null,
        userEducation: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      careerFairList: [],
      cascaderProps: {
        lazy: true,       // 启用懒加载
        lazyLoad: this.loadData,  // 加载数据的回调
        value: 'id',      // 值字段名
        label: 'name',    // 显示文本字段名
        leaf: 'isLeaf'    // 标识是否为叶子节点
      }
    };
  },
  created() {
    this.getList();
    this.getHireDicts();
    this.getCareerFairList();
  },
  computed: {
    isCompany() {
      return this.$store.state.user.roles[0] === 'company' && !!this.$store.state.user.userData.compId
    },
    companyId() {
      return this.$store.state.user.userData.compId
    },
  },
  methods: {
    /** 查询用户简历信息列表 */
    getList() {
      this.loading = true;
      listUserResume(this.queryParams).then(response => {
        response.rows.forEach(item => {
          item.isFollowText = item.isFollow === 1 ? '已关注' : '未关注'
          item.isRelateBool = item.isRelate === 1
        })
        this.userResumeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询招聘会管理列表 */
    getCareerFairList() {
      listCareerFair(this.queryParams).then(response => {
        this.careerFairList = response.rows;
      });
    },
    // 获取字典
    getHireDicts() {
      getHireDicts().then(res => {
        this.stationEduList = res.data.filter(item => item.field === 'stationEdu')[0].dicts
        this.workExperienceList = res.data.filter(item => item.field === 'stationLesson')[0].dicts
      })
    },
    // 二级联动
    async loadData(node, resolve) {
      const { level } = node

      try {
        let nodes = []
        
        // 第一级：加载一级分类
        if (level === 0) {
          const { rows } = await listCompany({
            pageNum: 1,
            pageSize: 999
          })
          // const resData = 
          nodes = rows.map(item => ({
            id: item.id,
            name: item.compName,
            isLeaf: false  // 非叶子节点（还有二级）
          }))

          console.log(nodes, 'resssss')

        }

        // 第二级：根据一级ID加载二级分类
        if (level === 1) {
          const parentId = node.data.id
          const { rows } = await listStation({
            compId: parentId,
            pageNum: 1,
            pageSize: 999
          })
          nodes = rows.map(item => ({
            id: item.id,
            name: item.stationName,
            isLeaf: true  // 叶子节点（最后一级）
          }))
        }

        resolve(nodes)
      } catch (error) {
        console.error('加载数据失败:', error)
        resolve([])
      }
    },

    handleSelectCascader(arr) {
      this.queryParams.compId = arr[0]
      this.queryParams.stationId = arr[1]
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.stationId = null;
      this.selectedValue = []
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const { id, stationId, careerId } = row
      this.showResume = true
      getUserResume(id, stationId, careerId).then(response => {
        this.resumeData = response.data;
      });

    },
    // 联系
    handleChangeStatus(item) {
      item.isRelate = item.isRelateBool ? 1 : 0
      updateCompanyResume(item).then(response => {
        this.$modal.msgSuccess("操作成功");
        this.getList();
      });
    },
    // 关注
    handleFollow() {
      const params = this.resumeData
      params.isFollow = this.resumeData.isFollow === 1 ? 0 : 1
      updateCompanyResume(params).then(res => {
        this.$modal.msgSuccess("操作成功");
        this.showResume = false
        this.getList();
      })
    },

    /** 导出按钮操作 */
    handleExport() {
      this.queryParams.compId = this.$store.state.user.userData.compId || ''
      const params = {
        ids: this.ids,
        ...this.queryParams
      }
      const downloadUrl = process.env.VUE_APP_BASE_API + '/system/userResume/export?' + this.serializeParams(params)
      console.log(this.queryParams, 'downloadUrl')
      window.open(downloadUrl)
    },

    // 列表导出
    handleExportList() {
      const params = {
        ids: this.ids.join(','),
        ...this.queryParams
      }
      console.log(this.serializeParams(params), 'params')

      this.download('system/userResume/exportExecl', params, `userResume_${new Date().getTime()}.xlsx`)
    },

    handleDownload(item) {
      window.open(process.env.VUE_APP_BASE_API + item.attachment)
    },
    serializeParams(params) {
      const searchParams = new URLSearchParams();
      for (const [key, value] of Object.entries(params)) {
        if (value) {
          searchParams.append(key, value);
        }
      }
      return searchParams.toString();
    }
  }
};
</script>
